import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;

/**
* @description: 945. 使数组唯一的最小增量
* @author hewei
* @date 2022/9/17 14:08
* @version 1.0
*/

public class MinIncrementForUnique {

    public int minIncrementForUnique1(int[] nums) {
        Arrays.sort(nums);
        Deque<Integer> queue = new LinkedList<>();
        int ans = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i - 1]) {
                queue.push(nums[i]);
            } else {
                int count = nums[i] - nums[i - 1] - 1;
                int temp = 1;
                while (!queue.isEmpty() && count > 0) {
                    Integer poll = queue.poll();
                    ans += nums[i - 1] + temp - poll;
                    ++temp;
                    --count;
                }
            }
        }
        int temp = 1;
        while (!queue.isEmpty()) {
            Integer poll = queue.poll();
            ans += nums[nums.length - 1] + temp - poll;
            ++temp;
        }
        return ans;
    }

    public int minIncrementForUnique(int[] nums) {
        Arrays.sort(nums);
        int ans = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] <= nums[i - 1]) {
                ans += nums[i - 1] - nums[i] + 1;
                nums[i] = nums[i - 1] + 1;
            }
        }
        return ans;
    }
}
